// import * as d3 from "https://cdn.skypack.dev/d3@7";

// function setPie(){
//     // svg = d3.select('#network')
//     my_data = [0,18,5,6,29]
//     var pie = d3.pie().value(d=>d).padAngle(0.25)(my_data)
//     var arcMaker = d3.arc()
//                     .innerRadius(50)
//                     .outerRadius(150)
//                     .cornerRadius(10)
//     var sacleColor = d3.scaleOrdinal(d3.schemeCategory10)
//                         .domain(pie.map(d=>d.index))

//     var g = d3.select('#pie')
//                 .enter('g')
//                 .attr('transform','translate(300,175)')
//     g.selectAll('path').data(pie)
//                         .enter()
//                         .append('path')
//                         .attr('d',arcMaker)
//                         .attr('fill',d=>sacleColor(d.index))

//     // const g = svg.selectAll(".pie")
//     //                 .data(my_data)
//     //                 .join("g")    
//     //                 .attr("class", "pie")
    
//     // const pg = g.selectAll("g")
//     //             .data(d => d3.pie()(d))
//     //             .join("g")

//     // const arc = d3.arc()
//     //             .outerRadius(20)
//     //             .innerRadius(10)
//     //             .cornerRadius(5)
//     // const circle = d3
//     // .arc()
//     // .startAngle(0)
//     // .endAngle(2 * Math.PI)
//     // .innerRadius(0) 

//     // const pie = d3.pie().padAngle(10);
//     // const arcs = pie(getOneDataTest());
//     // const g = svg.selectAll('.pie')
//     //             .data

// }

function getPieData(){

    var url = "/data/family_assoc_ratio1.json"
    var request = new XMLHttpRequest();
    request.open("get", url);/*设置请求方法与路径*/
    request.send(null);/*不发送数据到服务器*/
    request.onload = function () {/*XHR对象获取到返回信息后执行*/
        if (request.status == 200) {/*返回状态为200，即为数据获取成功*/
            json = JSON.parse(request.responseText);
            console.log(json)
            return json
        }
    }
    
}

function getOneDataTest(){
    return [0,18,5,6,29]
}

//window.addEventListener( "load", makePie )
function makePie() {
    var my_data = getOneDataTest()
    // 传入整个数组
    var pie = d3.pie().value(d=>d).padAngle(0.015)( my_data ) //<1>
    // .sort(null) 不排序
    //传入字典的key的所有value
    //var pie = d3.pie().value(d=>d.key).sort(null).padAngle(0.015)( data )
    var arcMaker = d3.arc()
        .innerRadius( 130 )
        .outerRadius( 150 )    
        .cornerRadius(5)
    //自定义颜色
    //colorArray = ["#5a81aa","#d5c4a6","#bc7056","#dabd5b","#adb9b7"]
    //var scaleColor = d3.scaleOrdinal( colorArray )
    //    .domain( pie.map(d=>d.index) ) 
    var scaleColor = d3.scaleOrdinal( d3.schemePastel2 )
    var svg = d3.select( "#pie" )                               
        .append( "g" ).attr( "transform", "translate(300, 175)" )

        svg.selectAll( "path" ).data( pie ).enter().append( "path" )
        .attr( "d", arcMaker )
        .attr( "fill", d=>scaleColor(d.index) )
}

//window.addEventListener("load",makeNetwork)
function makeNetwork(){
    width = 1000
     height = 1000
    var svg = d3.select("#network")
                .attr("viewBox", [0, 0, width, height]);

    // var data = getPieData()
    // console.log(data)
    var url = "/data/family_assoc_ratio1.json"
    var request = new XMLHttpRequest();
    request.open("get", url);/*设置请求方法与路径*/
    request.send(null);/*不发送数据到服务器*/
    request.onload = function () {/*XHR对象获取到返回信息后执行*/
        if (request.status == 200) {/*返回状态为200，即为数据获取成功*/
            data = JSON.parse(request.responseText);
            new_data = data.map(i => {
                let x = 100+20*Math.random()
                let y = 200+20*Math.random()
                let r = 50+50*Math.random()
                return {
                    id:i.family_id,
                    ratio:i.ratio,
                    x:x,
                    y:y,
                    r:r
                    
                }
            })
            //数据太多太卡了...
           , slice_data = new_data.slice(0,20)
            //console.log(new_data)
            //为每一个饼图建组
            
            // var g = svg.selectAll(".pie")
            //     .data(new_data)
            //     .join("g")
            //     .attr("class","pie")
            //     .attr("transform","translate(200,300)")
            
            // var pie = d3.pie().padAngle(0.015)
            // var scaleColor = d3.scaleOrdinal( d3.schemePastel2 )
            // //弧度
            // var arcMaker = d3.arc()
            //     .innerRadius( 80 )
            //     .outerRadius( 100 )
            //     .cornerRadius(5)
            // //为每一个饼图画路径
            // g.selectAll("circle")
            //     .join("circle")
            //     .attr('cx',d=>d.x)
            //     .attr('cy',d=>d.y )
            //     .attr('r', d=>d.r)
            //     .style("fill","#EFF1F1")
            // g.selectAll("path")
            //     .data(d=>pie(d.ratio))
            //     .enter()
            //     .append("path")
            //     .attr( "d", arcMaker )
            //     .attr( "fill", d=>scaleColor(d.index) )
        
            // var g = svg.append("g")
            //             .attr("transform","translate(300,200)")
            
            // var node = g.append("g")
            //     .selectAll("circle")
            //     .data(slice_data)
            //     .join("circle")
            //     .attr("cx",d=>d.x)
            //     .attr("cy",d=>d.y)
            //     .attr("r",d=>d.r)
            //     .attr("fill","#EFF1F1")
            var scaleColor = d3.scaleOrdinal( d3.schemePastel2 )
            //
            bubbles = data=>d3.pack()
                                .size([width,height])
                                .padding(3)(
                                    d3.hierarchy({children:data})
                                )
            //console.log(bubbles(slice_data).leaves())
            //var pie = d3.pie().padAngle(0.015)
            const g = svg.selectAll("g")
                            .data(bubbles(slice_data).leaves())
                            .join("g")
                            .attr("opacity", 1)
                            .attr("transform",d=>`translate(${300+d.data.x},${200+d.data.y})`)
                            .on("mouseover", (e, d) => {
                                g.transition().duration(500).attr("opacity", a => a === d ? 1 : 0.3)
                              })
                            .on("mouseout", () => { 
                            g.transition().duration(500).attr("opacity", 1);
                            })
            var drawPie = d => d3.arc()
                                .innerRadius(d.data.r-20)
                                .outerRadius(d.data.r-10)
                                .cornerRadius(10)
                                .startAngle(d.pie.startAngle)
                                .endAngle(d.pie.endAngle)
            g.append("g")
                .call(g=>g.append("circle").attr("r",d=>d.data.r).attr("fill","#EFF1F1"))
            g.append("g")
                .attr("class","pie")
                .selectAll("path")
                .data(d => d3.pie()(d.data.ratio).map(p => ({pie: p, data: d.data})))
                .join("path")
                .attr("d",d=>drawPie(d)())
                .attr("fill",(d,i)=>scaleColor(i))
            
            const simulation = d3.forceSimulation(slice_data)
            .force("collide", d3.forceCollide().radius(d => d.r + 1).strength(0))
            .force("x", d3.forceX().strength(0.01))
            .force("y", d3.forceY().strength(0.01))
            .on("tick", ticked)
            
            //Ramp up collision strength to provide smooth transition
            let duration = 2000
            let t = d3.timer(elapsed => {
                let dt = elapsed / duration
                simulation.force("collide").strength(dt)
                if (dt >= 1.0) t.stop()
            })//timer
            
            function ticked() {
                // node.selectAll("circle").attr("cx", d => d.data.x)
                //     .attr("cy", d => d.data.y)
                g.attr("transform",d=>`translate(${300+d.data.x},${200+d.data.y})`)
            }

            
        }
    }
    
}

//window.addEventListener("load",makeNetwork2)
function makeNetwork2(){
    width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
    //width = 1000
    height = width
    var svg = d3.select("#network")
                .attr("viewBox", [0, 0, width, height]);

    // var data = getPieData()
    // console.log(data)
    var url = "/data/family_assoc_ratio1.json"
    var request = new XMLHttpRequest();
    request.open("get", url);/*设置请求方法与路径*/
    request.send(null);/*不发送数据到服务器*/
    request.onload = function () {/*XHR对象获取到返回信息后执行*/
        if (request.status == 200) {/*返回状态为200，即为数据获取成功*/
            data = JSON.parse(request.responseText);
            new_data = data.map(i => {
                let x = 100+20*Math.random()
                let y = 100+20*Math.random()
                let r = 40+50*Math.random()
                return {
                    id:i.family_id,
                    ratio:i.ratio,
                    x:x,
                    y:y,
                    r:r
                    
                }
            })
            //数据太多太卡了...
           , slice_data = new_data.slice(0,10)
            var scaleColor = d3.scaleOrdinal( d3.schemePastel2 )
            //
            // bubbles = data=>d3.pack()
            //                     .size([width,height])
            //                     .padding(3)(
            //                         d3.hierarchy({children:data})
            //                     )
            //console.log(bubbles(slice_data).leaves())
            //var pie = d3.pie().padAngle(0.015)
            const g = svg.selectAll("g")
                            .data(slice_data)
                            .join("g")
                            .attr("opacity", 1)
                            .attr("transform",d=>`translate(${300+d.x},${200+d.y})`)
                            .on("mouseover", (e, d) => {
                                g.transition().duration(500).attr("opacity", a => a === d ? 1 : 0.3)
                              })
                            .on("mouseout", () => { 
                            g.transition().duration(500).attr("opacity", 1);
                            })
            var drawPie = d => d3.arc()
                                .innerRadius(d.data.r-16)
                                .outerRadius(d.data.r-8)
                                .cornerRadius(10)
                                .startAngle(d.pie.startAngle)
                                .endAngle(d.pie.endAngle)
            g.append("g")
                .call(g=>g.append("circle").attr("r",d=>d.r).attr("fill","#ADB9B7")).attr("opacity", 0.2)
            g.append("g")
                .attr("class","pie")
                .selectAll("path")
                .data(d => d3.pie()(d.ratio).map(p => ({pie: p, data: d})))
                .join("path")
                .attr("d",d=>drawPie(d)())
                .attr("fill",(d,i)=>scaleColor(i))
            
            const simulation = d3.forceSimulation(slice_data)
            .force("collide", d3.forceCollide().radius(d => d.r + 1).strength(0))
            .force("x", d3.forceX().strength(0.01))
            .force("y", d3.forceY().strength(0.01))
            .on("tick", ticked)
            
            //Ramp up collision strength to provide smooth transition
            let duration = 2000
            let t = d3.timer(elapsed => {
                let dt = elapsed / duration
                simulation.force("collide").strength(dt)
                if (dt >= 1.0) t.stop()
            })//timer
            
            function ticked() {
                // node.selectAll("circle").attr("cx", d => d.data.x)
                //     .attr("cy", d => d.data.y)
                g.attr("transform",d=>`translate(${300+d.x},${200+d.y})`)
            }

            
        }
    }
}
//data = FileAttachment("flare-2.json").json()

window.addEventListener("load",makeNetwork3)
function makeNetwork3(){
    width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
    height = width
    var svg = d3.select("#network")
                .attr("viewBox", [0, 0, width, height]);
    var url = "/data/family_assoc_ratio1.json"
    d3.json("/data/family_assoc_ratio1.json").then(
        function(data){
            new_data = data.map(i => {
                let x = 100+20*Math.random()
                let y = 100+20*Math.random()
                let r = 40+50*Math.random()
                return {
                    id:i.family_id,
                    ratio:i.ratio,
                    x:x,y:y,r:r
                }
            })
            slice_data = new_data.slice(0,10)
            var scaleColor = d3.scaleOrdinal( d3.schemePastel2 )

            const g = svg.selectAll("g")
                            .data(slice_data)
                            .join("g")
                            .attr("opacity", 1)
                            .attr("transform",d=>`translate(${300+d.x},${200+d.y})`)
                            .on("mouseover", (e, d) => {
                                g.transition().duration(500).attr("opacity", a => a === d ? 1 : 0.3)
                                })
                            .on("mouseout", () => { 
                                g.transition().duration(500).attr("opacity", 1);
                            })
            var drawPie = d => d3.arc()
                                .innerRadius(d.data.r-16)
                                .outerRadius(d.data.r-8)
                                .cornerRadius(10)
                                .startAngle(d.pie.startAngle)
                                .endAngle(d.pie.endAngle)()
            g.append("g")
                .call(g=>g.append("circle").attr("r",d=>d.r).attr("fill","#ADB9B7")).attr("opacity", 0.2)
            var p = g.append("g")
                .attr("class","pie")
                .selectAll("path")
                .data(d => d3.pie()(d.ratio).map(p => ({pie: p, data: d})))
                .join("path")
                .attr("d",d=>drawPie(d))
                .attr("fill",(d,i)=>scaleColor(i))
                .on('mouseover', (e,d) => {
                    p.transition().duration(500).attr("opacity", a => a === d ? 1 : 0.3).attr("cursor","pointer")
                  })
                .on('mouseout', (e,d) => {
                    p.transition().duration(500).attr("opacity", 1)
                })
            
            const simulation = d3.forceSimulation(slice_data)
            .force("collide", d3.forceCollide().radius(d => d.r + 1).strength(0))
            .force("x", d3.forceX().strength(0.01))
            .force("y", d3.forceY().strength(0.01))
            .on("tick", ticked)
            
            let duration = 5000
            let t = d3.timer(elapsed => {
                let dt = elapsed / duration
                simulation.force("collide").strength(dt)
                if (dt >= 1.0) t.stop()
            })//timer
            
            function ticked() {
                g.attr("transform",d=>`translate(${300+d.x},${200+d.y})`)
            }
        }
    )
}